package com.syyai.spring.boot.starter.demo;

import java.lang.reflect.Field;
import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

import com.syyai.spring.boot.starter.demo.util.NameUtil;

/**
 * 
 * @author zhangyongjie
 *
 */
@SpringBootApplication
@EnableConfigurationProperties(HibernateProperties.class)
public class App {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SpringApplication.run(App.class, args);
	}

	
	
	@Autowired
    private HibernateProperties hibernateProperties;
	
	@Bean
	@ConditionalOnMissingBean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource datasource() {
        return DataSourceBuilder.create().build();
    }
	
	
	
	@Bean
	@ConditionalOnMissingBean
	public LocalSessionFactoryBean  buildSessionFactory(DataSource dataSource,Properties properties){
		LocalSessionFactoryBean  sessionFactory = new org.springframework.orm.hibernate5.LocalSessionFactoryBean();
		sessionFactory.setDataSource(dataSource);
		sessionFactory.setPackagesToScan("com.bstek.uflo.model*");
		if(null == properties){
			properties = new Properties();
		}
		properties.setProperty("hibernate.hbm2ddl.auto", "update");
		properties.setProperty("hibernate.show_sql", "true");
		properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
		Field[] fields = hibernateProperties.getClass().getDeclaredFields();
		for (int j = 0; j < fields.length; j++) {
			fields[j].setAccessible(true);
			try {
				//System.out.println(fields[j].getName()+":"+fields[j].get(hibernateProperties));
				if(null != fields[j].get(hibernateProperties)){
					properties.setProperty( "hibernate."+NameUtil.humpToLine2(fields[j].getName()) , fields[j].get(hibernateProperties).toString()) ;
				}
			} catch (IllegalArgumentException e) {
				continue;
			} catch (IllegalAccessException e) {
				continue;
			}
		}
		sessionFactory.setHibernateProperties(properties);
		//properties.list(System.out);
		return sessionFactory;
	}
}
